//
//  TradeRecordsViewController.m
//  阿帕
//
//  Created by mac on 2020/1/2.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "TradeRecordsViewController.h"
#import "SearshBcTradeRecordVC.h"

#import "TradeRecordCell.h"
#import "BcTradeRecordCell.h"
#import "CollectionRecordController.h"

@interface TradeRecordsViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) NSDictionary *searchResultDic;

@end

static NSString *const cellID = @"BankCardCellID";

static const CGFloat cellHeight = 120;

@implementation TradeRecordsViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self setupBaseView];
    
    [self tradeRecordsListRequest];
}
- (void)rightBarItemClickAction{
    CollectionRecordController *recoreVC = [[CollectionRecordController alloc] init];
    recoreVC.accountType = self.accountType;
    [self.navigationController pushViewController:recoreVC animated:YES];
}
- (void)setupBaseView {
    
    self.navigationItem.title = @"交易记录";
    
    self.view.backgroundColor = BackgroundColor;
    
    if (_isOnlyBankRecord) {
        UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
        //默认按钮为蓝色  设置按钮为自己本身图片的颜色
        [searchButton setImage:[[UIImage imageNamed:@"gcy_icon_search_siji"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [searchButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [searchButton addTarget:self action:@selector(rightBarItemClick) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:searchButton];
        rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
        self.navigationItem.rightBarButtonItem = rightItem;
    } else{
        UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [searchButton setTitle:@"收款记录" forState:UIControlStateNormal];
        [searchButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
        [searchButton addTarget:self action:@selector(rightBarItemClickAction) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:searchButton];
        self.navigationItem.rightBarButtonItem = rightItem;
    }
    
    [self.view addSubview:self.tableView];
}

- (void)tradeRecordsListRequest {
    
    WEAKSELF
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params;
    NSString *urlString = @"";
    
    if (_isOnlyBankRecord) {
        
        if ([DCSpeedy isBlankDictionary:_searchResultDic]) {
            params = @{
                @"pageNum": [NSNumber numberWithInteger:_pageNum],
                @"pageSize": DEFULT_LOAD_NUM,
                @"payStatus": @"1",
                @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
                @"accountType":self.accountType,
                @"accountId": self.dataDic[@"accountId"],
                @"taxLocationCode": self.dataDic[@"taxLocationCode"]
            };
        } else {
            params = _searchResultDic;
        }
        
        
        urlString = CJStringWithFormat(@"%@/ntocc-tms-api/remitDefinite/queryListForDriver", [ReAddressDynamic shared].baseUrl);
        
    } else {
        
        params = @{
            @"pageNum": [NSNumber numberWithInteger:_pageNum],
            @"pageSize": DEFULT_LOAD_NUM,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            @"accountType":self.accountType
        };
        
        urlString = [NSString stringWithFormat:@"%@/ntocc-basic-api/shipmentPaidRecord", [ReAddressDynamic shared].baseUrl];
        
    }
    
    [HTTPManager getNetworkRequest:urlString withParameter:params withVC:self netName:@"交易记录列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            
            if (_isOnlyBankRecord) {
                [weakSelf.dataArray addObjectsFromArray:[BcTradeRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            } else {
                [weakSelf.dataArray addObjectsFromArray:[TradeRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            }
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
            //                [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:nil];
            
        } else {
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)rightBarItemClick{
    SearshBcTradeRecordVC *sbtrvc = [[SearshBcTradeRecordVC alloc] init];
    [self.navigationController pushViewController:sbtrvc animated:YES];
    sbtrvc.SearchResultBlock = ^(NSString * _Nonnull orderDetailNumber, NSString * _Nonnull isPayAdvance, NSString * _Nonnull gmtCreatedStart, NSString * _Nonnull gmtCreatedEnd) {
        
        _searchResultDic = @{
            @"orderDetailNumber": orderDetailNumber,
            @"isPayAdvance": isPayAdvance,
            @"gmtCreatedStart": gmtCreatedStart,
            @"gmtCreatedEnd": gmtCreatedEnd,
            @"pageNum": [NSNumber numberWithInteger:_pageNum],
            @"pageSize": DEFULT_LOAD_NUM,
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            @"accountType":self.accountType
        };
        
        [self tradeRecordsListRequest];
    };
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self tradeRecordsListRequest];
}

- (void)loadMoreData{
    _pageNum ++;
    [self tradeRecordsListRequest];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isOnlyBankRecord) {
        
        BcTradeRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BcTradeRecordCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataArray[indexPath.row];
        return cell;
        
    } else {
        
        TradeRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataArray[indexPath.row];
        return cell;
    }
    
    return nil;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isOnlyBankRecord) {
        return cellHeight + 60;
    }
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 10, ScreenW, ScreenH - NavHeight - MenuBarHeight - 10);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TradeRecordCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BcTradeRecordCell class]) bundle:nil] forCellReuseIdentifier:@"BcTradeRecordCell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        _foundImageView.centerY -= 60;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}


@end
